<template>
	<view class="page-container back-grey-light">
		<!-- 内容区域 -->
		<view v-if="cate==null || cate.extra!=1" class="prow-l main back-white">
			<!-- 动态内容盒子 -->
			<view class="content-box">
				<!-- 文本输入框 -->
				<textarea class="content-input" v-model="description" maxlength="150" auto-height="true"
					placeholder-style="fontSize: 32rpx;color: #999999;line-height: 40rpx;"
					placeholder="这一刻想说些...">
				</textarea>
				<!-- 字数盒子 -->
				<view class="row-box sb">
					<view class="row-box">
						<text class="s24 primary"># {{ cate.name }}</text>
					</view>
					<view class="row-box">
						<text>{{ description.length }}</text>
						<text class="s24 grey-light">/150</text>
					</view>
				</view>
			</view>
			
			<!-- 上传图片视频区域 -->
			<scroll-view scroll-x="true" style="white-space: nowrap;">
				<view class="pcol-l upload-grid">
					<view v-for="(item, index) in images" :key="index" class="upload-item">
						<image class="upload-image" :src="item" mode="aspectFill" @click.stop="previewImage(index, images)"></image>
						<view class="row-box center radius-circle icon-box">
							<u-icon name="close" color="#ffffff" size="28" :bold="true" @click.stop="removeImage(index)"></u-icon>
						</view>
					</view>
					<view v-if="video.tempFilePath" class="upload-item">
						<video class="upload-image" :src="video.tempFilePath" object-fit="fill" :page-gesture="true" :enable-play-gesture="true"></video>
						<!-- <image class="upload-image" :src="video.thumbTempFilePath" mode="aspectFill"></image> -->
						<view class="row-box center radius-circle icon-box">
							<u-icon name="close" color="#ffffff" size="28" :bold="true" @click.stop="removeVideo()"></u-icon>
						</view>
					</view>
					<view v-if="!video.tempFilePath && images.length<limitImage" class="upload-item" @click="selectUploadHandle()">
						<image class="upload-image" src="../static/upload_n.png" mode="aspectFill"></image>
					</view>
				</view>
			</scroll-view>
			<!-- 操作菜单 -->
			<u-action-sheet :list="uploadTypeList" v-model="showSelectAction" border-radius="20" :cancel-btn="true" @click="clickSelectType"></u-action-sheet>
			
			<view class="border-top-box">
				<view class="row-box">
					<u-icon class="mr-10" style="height: 40rpx;" name="phone" :color="primaryColor" :size="28"></u-icon>
					<text>联系方式</text>
					<text class="grey-light">（选填）</text>
				</view>
				<view v-if="openStatus" class="mt-base row-box contact-box">
					<view class="radius-base back-grey prow-l pcol-s" @click="showContactSelect=true">{{ contactArr[contactId-1].name }}</view>
					<u-input class="radius-base back-grey prow-l" :custom-style="{'width': '360rpx'}" v-model="contactNumber" type="text" :maxlength="20"
						height="58" placeholder="点击左侧可选" placeholder-style="color: #999;font-size: 28rpx;"/>
				</view>
				<view v-else class="mt-base row-box contact-box">
					<view class="radius-base back-grey prow-l pcol-s">手机号</view>
					<u-input class="radius-base back-grey prow-l" :custom-style="{'width': '360rpx'}" v-model="contactNumber" type="text" :maxlength="20"
						height="58" placeholder="请输入手机号" placeholder-style="color: #999;font-size: 28rpx;"/>
				</view>
			</view>
			<view class="row-box border-top-box" @click="goCollegeSelect()">
				<text class="mr-base">选择校区</text>
				<text v-if="schoolName">{{ schoolName }}</text>
				<text v-else class="grey-light">全部校区</text>
			</view>
			<view v-if="openStatus" class="row-box border-top-box" @click="switchTip('匿名发布')">
				<text class="mr-base">匿名发布</text>
				<u-switch v-model="isAnonymous" :disabled="!isAuthent" :active-color="primaryColor" size="40"></u-switch>
			</view>
			<view v-if="openStatus" class="row-box border-top-box" @click="switchTip('设置实名评论')">
				<text class="mr-base">实名评论</text>
				<u-switch v-model="isRealnameComment" :disabled="!isAuthent" :active-color="primaryColor" size="40"></u-switch>
			</view>
		</view>
		<view v-else class="prow-lg main back-white">
			<view class="col-box border-bottom-box">
				<text class="s32 bold mb-base">舍友昵称</text>
				<u-input v-model="nickname" type="text" maxlength="10" placeholder="请填写舍友昵称" placeholder-style="color: #999;font-size: 28rpx;"
					border="true" border-color="#ccc" />
			</view>
			<view class="col-box border-bottom-box">
				<text class="s32 bold mb-base">舍友性别</text>
				<u-radio-group v-model="sex">
					<u-radio
						v-for="(item, index) in sexArr" :key="index" 
						:name="item.value"
						shape="square"
						:active-color="primaryColor"
					>
						{{item.name}}
					</u-radio>
				</u-radio-group>
			</view>
			<view class="col-box border-bottom-box">
				<text class="s32 bold mb-base">舍友年级专业</text>
				<u-input v-model="grade" type="text" maxlength="10" placeholder="请填写舍友年级专业" placeholder-style="color: #999;font-size: 28rpx;"
					border="true" border-color="#ccc" />
			</view>
			<view class="col-box border-bottom-box">
				<text class="s32 bold mb-base">舍友介绍</text>
				<u-input v-model="desc" type="textarea" maxlength="10" placeholder="请填写舍友介绍" placeholder-style="color: #999;font-size: 28rpx;"
					border="true" border-color="#ccc" />
			</view>
			<view class="col-box border-bottom-box">
				<text class="s32 bold mb-base">舍友喜欢类型</text>
				<u-input v-model="desc" type="text" maxlength="10" placeholder="请填写舍友喜欢类型" placeholder-style="color: #999;font-size: 28rpx;"
					border="true" border-color="#ccc" />
			</view>
			<view class="col-box border-bottom-box">
				<text class="s32 bold mb-base">舍友照片</text>
				<!-- 上传图片区域 -->
				<scroll-view scroll-x="true" style="white-space: nowrap;">
					<view class="pcol-l upload-grid">
						<view v-for="(item, index) in images" :key="index" class="upload-item">
							<image class="upload-image" :src="item" mode="aspectFill" @click.stop="previewImage(index, images)"></image>
							<view class="row-box center radius-circle icon-box">
								<u-icon name="close" color="#ffffff" size="28" :bold="true" @click.stop="removeImage(index)"></u-icon>
							</view>
						</view>
						<view v-if="images.length<limitImage" class="upload-item" @click="selectUploadHandle()">
							<image class="upload-image" src="/static/icon/upload.png" mode="aspectFill"></image>
						</view>
					</view>
				</scroll-view>
			</view>
		</view>
			
		<!-- 发布分类选择 -->
		<u-select
			v-model="showContactSelect"
			:list="contactArr"
			value-name="id"
			label-name="name"
			title="请选择联系方式"
			confirm-text="确认"
			:confirm-color="primaryColor"
			@confirm="selectContactType">
		</u-select>
		
		<!-- 提交按钮 -->
		<view class="submit-button-box">
			<view class="submit-button back-primary" @click="submitHandle()">发布</view>
		</view>
	</view>
</template>

<script>
	import env from '@/utils/env.js'
	import { mapState, mapMutations } from "vuex"
	export default {
		data() {
			return {
				cate: null, // 发布分类
				
				description: '', // 动态内容
				
				uploadTypeList: [
					{ text: '选择视频', fontSize: 32 },
					{ text: '选择图片', fontSize: 32 },
				], // 选择图片前操作菜单
				showSelectAction: false, // 是否显示选择图片前操作菜单
				
				qntoken: '',  // 七牛云上传token
				limitVideo: 1, // 视频最多1个
				limitImage: 6, // 图片最多6个
				video: {
					tempFilePath: '', // 视频临时地址
					thumbTempFilePath: '', // 视频封面临时地址
					width: 0, // 宽
					height: 0, // 高
				}, // 选择的视频
				upload: '', // 上传后视频
				videoCover: '', // 上传后视频封面
				
				images: [], // 上传图片列表(选择图片后的临时地址列表)
				uploads: [],  // 上传后列表
				imageInfo: {}, // 图片动态封面信息
				
				contactId: 3, // 联系方式类型 1:wx,2:qq,3.phone
				contactArr: [ {id: 1, name: '微信'}, {id: 2, name: 'QQ'}, {id: 3, name: '手机'}],
				showContactSelect: false, // 是否展示联系方式选择
				contactNumber: '', // 联系方式内容
				schoolId: null, // 选择的学校id
				schoolName: '', // 选择的学校name
				isAnonymous: false, // 开启匿名发布
				isRealnameComment: false, // 开启实名评论
				
				// -------------
				nickname: '', // 舍友昵称
				sex: 1, // 舍友性别
				sexArr: [ {name: '男', value: 1}, {name: '女', value: 0}  ], // 性别数组
				grade: '', // 舍友年级专业
				desc: '', // 舍友介绍
				typeDesc: '', // 舍友喜欢类型
				
			};
		},
		computed: {
			...mapState('m_user', ['isAuthent', 'openStatus']),
			
			// 视频上传完成标识
			videoUploadFlag() {
				let flag = 0
				if (this.upload) flag += 1
				if (this.videoCover) flag += 1
				return flag
			}
		},
		watch: {
			// 侦听图片选择列表
			images(newValue, oldValue) {
				if (this.images.length) {
					uni.getImageInfo({
						src: this.images[0],
						success: res => {
							return this.imageInfo = res
						}
					})
				}
			},
			
			// 侦听图片上传后地址列表
			uploads(newValue, oldValue) {
				if ((newValue.length == this.images.length) && this.images.length!=0) {
					// 上传完所有图片
					// 调用提交接口
					this.submit()
				}
			},
			
			// 侦听视频上传完成标识
			videoUploadFlag(newValue, oldValue) {
				if (newValue == 2) {
					// 上传完视频和视频封面
					// 调用提交接口
					this.submit()
				}
			}
		},
		onLoad(options) {
			console.log();
			this.cate = JSON.parse(options.cate)
			// 获取开关状态
			this.getStatus()
			// 获取七牛上传使用TOKEN
			this.getUploadToken()
		},
		methods: {
			...mapMutations('m_user', ['updateOpenStatus']),
			
			// 获取开关状态
			async getStatus() {
				// 获取开关状态
				let openStatus = await this.getOpenStatus()
				this.updateOpenStatus(openStatus)
			},
			
			// 点击上传引导
			async selectUploadHandle() {
				if (this.images.length == 0) { // 什么都没选择
					// 打开操作菜单
					this.showSelectAction = true
				} else if (this.images.length > 0) { // 选择了图片
					let count = this.limitImage - this.images.length
					this.images = [...this.images, ...await this.chooseImages(count)]
				}
			},
			// 点击选择上传类型
			async clickSelectType(index) {
				if (index == 0) { // 上传视频
					this.video = await this.chooseSingelVideo()
				} else if (index == 1) { // 上传图片
					let count = this.limitImage - this.images.length
					this.images = [...this.images, ...await this.chooseImages(count)]
				}
			},
			
			// 跳转选择学校
			goCollegeSelect() {
				uni.navigateTo({
					url: '/pages/subPackage/platform/college_list/college_list'
				})
			},
			
			// 选择联系方式
			selectContactType(e) {
				this.contactId = e[0].value
			},
			
			// 匿名发布和实名评论开关提示
			switchTip(tip) {
				if (!this.isAuthent) { // 如果用户未实名
					uni.showModal({
						content: `未实名不能${tip}！确定前往实名？`,
						confirmColor: this.primaryColor,
						success: (res) => {
							if (res.confirm) {
								uni.navigateTo({
									url: `/pages/subPackage/user/my_userinfo_bind/my_userinfo_bind?type=${2}`
								})
							}
						}
					})
				}
			},
			
			// 点击提交
			submitHandle() {
				if (!this.isAuthent) { // 如果用户未实名
					uni.showModal({
						content: `未实名不能发布！确定前往实名？`,
						confirmColor: this.primaryColor,
						success: (res) => {
							if (res.confirm) {
								uni.navigateTo({
									url: `/pages/subPackage/user/my_userinfo_bind/my_userinfo_bind?type=${2}`
								})
							}
						}
					})
				} else if (!this.description) {
					return uni.showToast({
						icon: 'none',
						title: '未填写内容！'
					})
				}
				
				uni.showLoading({
					title: '提交中...',
					mask: true
				})
				
				// 获取临时文件列表长度
				const length = this.images.length
				
				if (length > 0) { // 如果用户选择了图片
					
					// 先上传图片，上传完所有图片再调用提交的接口
					this.images.forEach((tempPath, index) => {
						let pathArr = tempPath.split('.')
						let extra = pathArr[pathArr.length-1]
						// 获得唯一标识码
						let uniqueCode = this.generateUUID()
						// case 'ECN': uploadURL = 'https://up.qiniup.com'
						// case 'NCN': uploadURL = 'https://up-z1.qiniup.com'
						// case 'SCN': uploadURL = 'https://up-z2.qiniup.com'
						// case 'NA': uploadURL = 'https://up-na0.qiniup.com'
						// case 'ASG': uploadURL = 'https://up-as0.qiniup.com'
						uni.uploadFile({
							url: 'https://up-z2.qiniup.com',
							filePath: tempPath,
							name: 'file',
							formData: {
								'key': uniqueCode + '.' + extra,
								'token': this.qntoken,
							},
							success: (res) => {
								console.log('uni.uploadFile', res)
								let strToObj = JSON.parse(res.data)
								let backUrl = env.imageUrl + strToObj.key
								// 处理上传成功后的返回值
								this.uploads.push(backUrl)
							},
							fail: (err) => {
								console.log('uni.uploadFile', err)
								uni.hideLoading()
								uni.showToast({
									icon: 'none',
									title: '上传出错，提交失败！'
								})
							}
						})
					})
				} else if (this.video.tempFilePath) { // 用户选择了视频
					
					// 上传视频
					let pathArr = this.video.tempFilePath.split('.')
					let extra = pathArr[pathArr.length-1]
					// 获得唯一标识码
					let uniqueCode = this.generateUUID()
					uni.uploadFile({
						url: 'https://up-z2.qiniup.com',
						filePath: this.video.tempFilePath,
						name: 'file',
						formData: {
							'key': uniqueCode + '.' + extra,
							'token': this.qntoken,
						},
						success: (res) => {
							console.log('uni.uploadFile', res)
							let strToObj = JSON.parse(res.data)
							let backUrl = env.imageUrl + strToObj.key
							// 处理上传成功后的返回值
							this.upload = backUrl
						},
						fail: (err) => {
							console.log('uni.uploadFile', err)
							uni.hideLoading()
							uni.showToast({
								icon: 'none',
								title: '上传出错，发布失败！'
							})
						}
					})
					
					// 上传封面
					let pathArr2 = this.video.thumbTempFilePath.split('.')
					let extra2 = pathArr2[pathArr2.length-1]
					// 获得唯一标识码
					let uniqueCode2 = this.generateUUID()
					uni.uploadFile({
						url: 'https://up-z2.qiniup.com',
						filePath: this.video.thumbTempFilePath,
						name: 'file',
						formData: {
							'key': uniqueCode2 + '.' + extra2,
							'token': this.qntoken,
						},
						success: (res) => {
							console.log('uni.uploadFile', res)
							let strToObj = JSON.parse(res.data)
							let backUrl = env.imageUrl + strToObj.key
							// 处理上传成功后的返回值
							this.videoCover = backUrl
						},
						fail: (err) => {
							console.log('uni.uploadFile', err)
							uni.hideLoading()
							uni.showToast({
								icon: 'none',
								title: '上传出错，发布失败！'
							})
						}
					})
				} else { // 图片视频都没选
					// 调用提交接口
					this.submit()
				}
			},
			
			// 提交接口
			submit() {
				let params = {}
				params['typeId'] = this.cate.id
				params['description'] = this.description
				params['coverImage'] = this.upload ? this.videoCover : this.uploads[0]
				params['width'] = this.upload ? this.video.width : this.imageInfo.width
				params['height'] = this.upload ? this.video.height : this.imageInfo.height
				params['schoolId'] = this.schoolId
				params['isAnonymous'] = this.isAnonymous?1:0
				params['isRealnameComment'] = this.isRealnameComment?1:0
				if (this.uploads.length) params['images'] = this.uploads.join(',')
				if (this.upload) params['video'] = this.upload
				if (this.contactId && this.contactNumber) {
					params['contactId'] = this.contactId
					params['contactNumber'] = this.contactNumber
				}
				this.$api.AddPost(params).then(res => {
					console.log('AddPost-success', res)
					uni.hideLoading()
					if (res.data.code == 200) {
						uni.showToast({
							icon: 'none',
							title: '发布成功！',
							success: () => {
								setTimeout(() => {
									uni.navigateBack({
										delta: 1,
										success: () => {
											uni.navigateTo({
												url: '/pages/subPackage/user/my_post/my_post'
											})
										}
									})
								}, 500)
							}
						})
					} else {
						uni.showToast({
							icon: 'none',
							title: res.data.msg
						})
					}
				}).catch(err => {
					console.log('AddPost-fail', err)
					uni.hideLoading()
					uni.showToast({
						icon: 'none',
						title: '发布失败！'
					})
				})
				
			}
		},
	}
</script>

<style lang="scss">
// 内容区域
	.main {
		padding-top: 24rpx;
	}
	// 动态内容盒子
	.content-box {
		position: relative;
		// 文本输入框
		.content-input {
			width: 100%;
			min-height: 286rpx;
			fontSize: 28rpx;
			line-height: 40rpx;
		}
	}
	// 操作菜单
	.u-action-sheet-item {
		text {
			font-size: 32rpx;
		}
	}
	
	// 额外信息
	.border-top-box {
		padding: 30rpx 0;
		border-top: 1rpx solid #f3f3f3;
	}
	// 联系方式盒子
	.contact-box {
		display: grid;
		grid-template-columns: 120rpx 1fr;
		grid-template-rows: 60rpx;
		column-gap: 20rpx;
		.back-grey {
			&:first-child {
				color: $uni-text-color;
			}
			&:last-child {
				color: $uni-text-color-grey-light;
			}
		}
	}
	// 另一种发布帖子样式
	.border-bottom-box {
		padding: 30rpx 0;
		border-bottom: 1rpx solid #f3f3f3;
		
	}
</style>
